/*
Copyright (c) 2012 the VATSIM Connector project

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "planestax.h"
#include "xpinn.h"
#include <fstream>
#include <XPLMUtilities.h>

void XPInnPlanesTaxonomy::reloadDesignators(std::string const& filename)
{
  reloadDesignators(std::ifstream(filename), filename);
}

void XPInnPlanesTaxonomy::reloadDesignators(std::istream& file, std::string const& filename)
{
  if (! file.good())
  {
    //TODO error
  }
  else
  {
    m_designators.clear();

    int line = 0;
    do
    {
      static int const max = 512;
      char buf[max];
      file.getline(buf, max);

      if (file.gcount() < max)
      {
	if (file.gcount() > 0 && buf[0] != '#')
	  parseDesignator(buf, filename, line);
      }
      else
      {
	//TODO error
      }
      line++;
    } while (file.good());
  }
}

void XPInnPlanesTaxonomy::reloadPlanes(std::string const& filename)
{
  reloadPlanes(std::ifstream(filename), filename);
}

void XPInnPlanesTaxonomy::reloadPlanes(std::istream& file, std::string const& filename)
{
  if (! file.good())
  {
    //TODO error
  }
  else
  {
    m_tree.clear();

    int line = 0;
    do
    {
      static int const max = 512;
      char buf[max];
      file.getline(buf, max);

      if (file.gcount() < max)
      {
	if (file.gcount() > 0 && buf[0] != '#')
	  parsePlane(buf, filename, line);
      }
      else
      {
	//TODO error
      }
      line++;
    } while (file.good());
  }
}

void XPInnPlanesTaxonomy::parseDesignator(std::string const& line, std::string const& filename, int linenum)
{
  std::list<std::string> fields = xpinnSplit< std::list<std::string> > (line, '\t');
  if (fields.size() >= 7)
  {
    if (fields.size() > 7)
    {
      //TODO warning
    }

    std::string type = fields.front(); fields.pop_front();
    std::string minmatch = fields.front(); fields.pop_front();
    fields.reverse();

    m_designators[type] = Designator(fields, std::strtoul(minmatch.c_str(), 0, 10));
  }
  else
  {
    //TODO warning
  }
}

void XPInnPlanesTaxonomy::parsePlane(std::string const& line, std::string const& filename, int linenum)
{
  std::vector<std::string> const fields = xpinnSplit< std::vector<std::string> > (line, '\t');
  if (fields.size() != 4)
  {
    //TODO error
    return;
  }

  std::string const& type = fields[0];
  std::string const& airline = fields[1];
  std::string const& source = fields[2];
  std::string path = fields[3];

  map_type::const_iterator desigIt = m_designators.find(type);
  if (desigIt == m_designators.end())
  {
    //TODO error
    return;
  }

  if (source == "LIB")
  {
    std::vector<std::string> objs = xpinnLookupObjects(path);
    if (objs.size() > 0) path = objs[0];
    else
    {
      //TODO error
      return;
    }
  }
  else if (source == "ABS")
  {
    path = xpinnGetSystemPath() + xpinnToPlatformPath(path);
  }
  else if (source == "REL")
  {
    path = xpinnSplitPath(filename).first + XPLMGetDirectorySeparator() + xpinnToPlatformPath(path);
  }
  else if (source == "SYS")
  {
  }
  else
  {
    //TODO error
    return;
  }

  std::vector<std::string> const airlines = xpinnSplit< std::vector<std::string> > (airline, '|');
  for (std::vector<std::string>::const_iterator airlineIt = airlines.begin(); airlineIt != airlines.end(); ++airlineIt)
  {
    std::list<std::string> taxa = desigIt->second.m_taxa;
    taxa.push_front(*airlineIt);

    m_tree.insert(taxa, path);
  }
}

std::string XPInnPlanesTaxonomy::getClosestMatch(std::string const& type, std::string const& airline)
{
  std::map<std::string, Designator>::const_iterator desigIt = m_designators.find(type);
  if (desigIt == m_designators.end()) desigIt = m_designators.find("ZZZZ");
  if (desigIt == m_designators.end()) return "";
  Designator const& desig = desigIt->second;

  unsigned size = desig.m_taxa.size() + 1;
  std::list<std::string> taxa = desig.m_taxa; // make a copy
  taxa.push_front(airline);
  {
    Tree<std::string, std::string> const& tree = m_tree.descend(taxa);
    if (size - taxa.size() >= desig.m_minmatch) // matched close enough
    {
      return tree.get();
    }
  }

  taxa = desig.m_taxa; // make another copy
  taxa.push_front("YYY");
  {
    Tree<std::string, std::string> const& tree = m_tree.descend(taxa);
    return tree.get(); // the closest match under the catch-all livery
  }
  return "";
}

void XPInnPlanesTaxonomy::visitDesignators(std::function<void(std::string const&, std::list<std::string> const&, unsigned)> const& fn) const
{
  for (std::map<std::string, Designator>::const_iterator it = m_designators.begin(); it != m_designators.end(); ++it)
  {
    fn(it->first, it->second.m_taxa, it->second.m_minmatch);
  }
}

void XPInnPlanesTaxonomy::visitPlanes(std::function<void(std::string const&, std::list<std::string> const&)> const& fn) const
{
  m_tree.visit(fn);
}